package com.example.demo;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CodeGenerator {

    // 配置常量
    private static final String AUTHOR = "bianyuwu";// 作者
    private static final String TABLE_NAME = "YW_OUTPUT_FORM";// 表名
    private static final String KEY_FIELD = "OUTPUT_ID";// 主键 QUALITY_NORM_ID
    private static final String ORDER_FIELD = "CREATE_TIME";// 排序字段

    private static final String MODULE_NAME = "business";// 模块名
    private static final String PARENT_PACKAGE_PATH = "com.rdkl.printing";// 基本包路径


    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(AUTHOR);
        gc.setOpen(false);
        gc.setServiceImplName("%sService");
        gc.setMapperName("%sDao");
        gc.setDateType(DateType.TIME_PACK);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:oracle:thin:@//192.168.1.201:1521/hupub7");
        // dsc.setSchemaName("public");
        dsc.setDriverName("oracle.jdbc.OracleDriver");
        dsc.setUsername("db_sp_test");
        dsc.setPassword("admin123");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setModuleName(MODULE_NAME);
        pc.setParent(PARENT_PACKAGE_PATH);
        pc.setEntity("model");
        pc.setMapper("dao");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String,Object> map = new HashMap<>();
                map.put("basePackage", pc.getParent());
                map.put("className", this.getConfig().getGlobalConfig().getAuthor());
                map.put("moduleName", MODULE_NAME);
                map.put("keyField", KEY_FIELD);
                map.put("keyFieldHump", lineToHump(KEY_FIELD));
                map.put("orderField", ORDER_FIELD);
                map.put("rootPath", PARENT_PACKAGE_PATH);
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = getFileOutConfigs(projectPath, pc);
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setController("/templates/controller");
        templateConfig.setServiceImpl("/templates/service");
        templateConfig.setMapper("/templates/dao");
        templateConfig.setService(null);
        templateConfig.setEntity(null);
        templateConfig.setXml("/templates/xml");
        //templateConfig.setController("/templates/controller");

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();
        //templateConfig.setXml(null);


        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setTablePrefix("YW_");

        // 公共父类
        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        //strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setInclude(TABLE_NAME);
        strategy.setControllerMappingHyphenStyle(true);
       // strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);


        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 自定义输出文件
     *
     * @Author bianyuwu
     * @Date 2019/8/7 16:34
     */
    private static List<FileOutConfig> getFileOutConfigs(String projectPath, PackageConfig pc) {
        // 如果模板引擎是 freemarker
        String templatePathHtml = "/templates/js.ftl";
        String templatePathDto = "/templates/dto.ftl";
        String templatePathList = "/templates/list.ftl";
        String templatePathForm = "/templates/form.ftl";
        String templatePathFormJs = "/templates/formJs.ftl";
        String templatePathModel = "/templates/model.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePathHtml) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                String name = StringUtils.firstCharToLower(tableInfo.getEntityName());
                return projectPath + "/src/main/resources/dist/" + name + ".js";
            }
        });
        focList.add(new FileOutConfig(templatePathDto) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/dist/" + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(templatePathList) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String name = StringUtils.firstCharToLower(tableInfo.getEntityName());
                return projectPath + "/src/main/resources/dist/" + name + "_list.ftl";
            }
        });
        focList.add(new FileOutConfig(templatePathForm) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String name = StringUtils.firstCharToLower(tableInfo.getEntityName());
                return projectPath + "/src/main/resources/dist/" + name + "_form.ftl";
            }
        });
        focList.add(new FileOutConfig(templatePathFormJs) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String name = StringUtils.firstCharToLower(tableInfo.getEntityName());
                return projectPath + "/src/main/resources/dist/" + name + "_form.js";
            }
        });
        focList.add(new FileOutConfig(templatePathModel) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/dist/" + tableInfo.getEntityName() + ".java";
            }
        });
        return focList;
    }

    public static String lineToHump(String str) {
        Pattern linePattern = Pattern.compile("_(\\w)");
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
